<?php

/**
 * @version    $Id: functions.php 1 2016-07-19 08:45:53Z tic $
 *  自定义函数库
 */
include CORE . DS . 'dede.func.php';

function replace_word($list_rword, $body) {
    foreach ($list_rword as $r) {
        if ($r['type'] == 1) {
            $body = str_replace($r['oldword'], $r['newword'], $body);
        } elseif ($r['type'] == 2) {
            $body = str_replace($r['oldword'], '#@replace@#', $body);
            $body = str_replace($r['newword'], $r['oldword'], $body);
            $body = str_replace('#@replace@#', $r['newword'], $body);
        }
    }
    return $body;
}

function __autoload($class) {
    if (is_file(CORE . DS . $class . '.crypt.php')) {
        include CORE . DS . $class . '.crypt.php';
    } else if (is_file(CORE . DS . $class . '.class.php')) {
        include CORE . DS . $class . '.class.php';
    } elseif (is_file(ROOT . DS . 'class' . DS . $class . '.class.php')) {
        include ROOT . DS . 'class' . DS . $class . '.class.php';
    }
}

function gp($key, $filter = true) {
    if (strpos($key, ',') !== false) {
        $keys = explode(',', $key);
        foreach ($keys as $key)
            $tmp[$key] = gp($key, $filter);
        return $tmp;
    }
    if (isset($_REQUEST[$key])) {
        $value = $_REQUEST[$key];
        if (is_string($filter) && !validate::$filter($value)) {
            $value = false;
        } elseif ($filter === true) {
            filter::check_disallow_char($value);
            return safe_replace($value);
        } else {
            filter::check_disallow_char($value);
        }
    } else {
        $value = null;
    }
    return $value;
}

function safe_replace($string) {
    if (empty($string))
        return $string;
    if (is_array($string))
        return array_map('safe_replace', $string);
    $string = str_replace('%20', '', $string);
    $string = str_replace('%27', '', $string);
    $string = str_replace('%2527', '', $string);
    $string = str_replace('*', '', $string);
    $string = str_replace('#', '', $string);
    $string = str_replace('%', '', $string);
    $string = str_replace(';', '', $string);
    $string = str_replace('&', '&amp;', $string);
    $string = str_replace('"', '&quot;', $string);
    $string = str_replace("'", '&#039;', $string);
    $string = str_replace('<', '&lt;', $string);
    $string = str_replace('>', '&gt;', $string);
    $string = str_replace("{", '', $string);
    $string = str_replace('}', '', $string);
    $string = str_replace('\\', '', $string);
    return $string;
}

// 浏览器友好的变量输出
function dump($var, $echo = true, $label = null, $strict = true) {
    $label = ($label === null) ? '' : rtrim($label) . ' ';
    if (!$strict) {
        if (ini_get('html_errors')) {
            $output = print_r($var, true);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        } else {
            $output = $label . print_r($var, true);
        }
    } else {
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if (!extension_loaded('xdebug')) {
            $output = preg_replace("/\]\=\>\n(\s+)/m", '] => ', $output);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        }
    }
    if ($echo) {
        echo($output);
        return null;
    } else
        return $output;
}

function get_url() {
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
    return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
}

function get_client_ip() {
    $ip = $_SERVER['REMOTE_ADDR'];
    if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
        foreach ($matches[0] AS $xip) {
            if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                $ip = $xip;
                break;
            }
        }
    }
    return $ip;
}

function cut($string, $length, $dot = '') {
    $string = strip_tags($string);
    if (strlen($string) <= $length) {
        return $string;
    }
    $pre = chr(1);
    $end = chr(1);
    $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;', '&nbsp;'), array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end, $pre . ' ' . $end), $string);
    $strcut = '';
    $n = $tn = $noc = 0;
    while ($n < strlen($string)) {
        $t = ord($string[$n]);
        if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
            $tn = 1;
            $n++;
            $noc++;
        } elseif (194 <= $t && $t <= 223) {
            $tn = 2;
            $n += 2;
            $noc += 2;
        } elseif (224 <= $t && $t <= 239) {
            $tn = 3;
            $n += 3;
            $noc += 2;
        } elseif (240 <= $t && $t <= 247) {
            $tn = 4;
            $n += 4;
            $noc += 2;
        } elseif (248 <= $t && $t <= 251) {
            $tn = 5;
            $n += 5;
            $noc += 2;
        } elseif ($t == 252 || $t == 253) {
            $tn = 6;
            $n += 6;
            $noc += 2;
        } else {
            $n++;
        }
        if ($noc >= $length) {
            break;
        }
    }
    if ($noc > $length) {
        $n -= $tn;
    }
    $strcut = substr($string, 0, $n);
    $strcut = str_replace(array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end, $pre . ' ' . $end), array('&amp;', '&quot;', '&lt;', '&gt;', '&nbsp;'), $strcut);
    $pos = strrpos($strcut, chr(1));
    if ($pos !== false) {
        $strcut = substr($strcut, 0, $pos);
    }
    return $strcut . $dot;
}

function formatsize($bytes) {
    $units = array(0 => 'B', 1 => 'kB', 2 => 'MB', 3 => 'GB');
    $log = log($bytes, 1024);
    $power = (int) $log;
    $size = pow(1024, $log - $power);
    return round($size, 2) . ' ' . $units[$power];
}

function curl_get_contents($url, $referer = '') {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 10000);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 3000);
    if ($referer) {
        curl_setopt($ch, CURLOPT_REFERER, $referer);
    }
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function get_domain($str) {
    $gjExt = explode(',', 'ad,ae,af,ag,ai,al,am,an,ao,aq,ar,as,at,au,aw,az,ba,bb,bd,be,bf,bg,bh,bi,bj,bm,bn,bo,br,bs,bt,bv,bw,by,bz,ca,cc,cf,cg,ch,ci,ck,cl,cm,cn,co,cq,cr,cu,cv,cx,cy,cz,de,dj,dk,dm,do,dz,ec,ee,eg,eh,es,et,ev,fi,fj,fk,fm,fo,fr,ga,gb,gd,ge,gf,gh,gi,gl,gm,gn,gp,gr,gt,gu,gw,gy,hk,hm,hn,hr,ht,hu,id,ie,il,in,io,iq,ir,is,it,jm,jo,jp,ke,kg,kh,ki,km,kn,kp,kr,kw,ky,kz,la,lb,lc,li,lk,lr,ls,lt,lu,lv,ly,ma,mc,me,md,mg,mh,ml,mm,mn,mo,mp,mq,mr,ms,mt,mv,mw,mx,my,mz,na,nc,ne,nf,ng,ni,nl,no,np,nr,nt,nu,nz,om,pa,pe,pf,pg,ph,pk,pl,pm,pn,pr,pt,pw,py,qa,re,ro,ru,rw,sa,sb,sc,sd,se,sg,sh,si,sj,sk,sl,sm,sn,so,sr,st,su,sy,sz,tc,td,tf,tg,th,tj,tk,tl,tm,tn,to,tp,tr,tt,tv,tw,tz,ua,ug,uk,us,uy,va,vc,ve,vg,vn,vu,wf,ws,ye,yu,za,zm,zr,zw,gs');
    $sfExt = explode(',', 'js,cq,xj,sc,sd,ln,bj,yn,gs,gd,zj,he,tw,gz,ha,jl,sh,qh,gx,ah,sx,fj,hk,xz,hb,hl,tj,nx,hi,jx,nm,ac,mo,sn,hn');

    $str = preg_replace('#^.*?(http://|https://)#', '', $str);
    $str = preg_replace('#(\:|/).*?$#', '', $str);
    $str = strtolower(trim($str));
    if ($str && preg_match('#^[a-z0-9_\-\.]*$#', $str)) {
        $tmp = array();
        $sps = explode('.', $str);
        $last = array_pop($sps);
        //国别域名
        if (in_array($last, $gjExt)) {
            $tmp[] = $last;
            if ($sec = array_pop($sps)) {
                //国家内部域名
                if (in_array($sec, array('com', 'org', 'gov', 'net', 'edu'))) {
                    $tmp[] = $sec;
                    //中国省份域名
                } elseif ($tmp[0] == 'cn' && in_array($sec, $sfExt)) {
                    $tmp[] = $sec;
                } else {
                    array_push($sps, $sec);
                }
            } else {
                return false;
            }
        } else {
            //直接是域名了
            $tmp[] = $last;
        }
        //实际域名名称
        if ($name = array_pop($sps)) {
            $tmp[] = $name;
            $tmp = array_reverse($tmp);
            return join('.', $tmp);
        }
    }
    return false;
}

function logging_run($log, $type = 'trace', $filename = 'run') {
    $filename = DATA . '/log/' . $filename . '_' . date('Ymd') . '.log';
    mkdirs(dirname($filename));
    $logFormat = "%date %type %user %url %context";
    if (!empty($GLOBALS['_POST'])) {
        $context[] = logging_implode($GLOBALS['_POST']);
    }
    if (is_array($log)) {
        $context[] = logging_implode($log);
    } else {
        $context[] = preg_replace('/[ \t\r\n]+/', ' ', $log);
    }
    $log = str_replace(explode(' ', $logFormat), array(
        '[' . date('Y-m-d H:i:s', time()) . ']',
        $type,
        $_SERVER["PHP_SELF"] . "?" . $_SERVER["QUERY_STRING"],
        implode("\n", $context),
            ), $logFormat);
    file_put_contents($filename, $log . "\r\n", FILE_APPEND);
    return true;
}

function logging_implode($array, $skip = array()) {
    $return = '';
    if (is_array($array) && !empty($array)) {
        foreach ($array as $key => $value) {
            if (empty($skip) || !in_array($key, $skip, true)) {
                if (is_array($value)) {
                    $return .= $key . '={' . logging_implode($value, $skip) . '}; ';
                } else {
                    $return .= "$key=$value; ";
                }
            }
        }
    }
    return $return;
}

function mkdirs($path) {

    if (!is_dir($path)) {

        mkdirs(dirname($path));

        mkdir($path, 0777);
    }

    return is_dir($path);
}

function is_mobile() {
    $useragent = $_SERVER['HTTP_USER_AGENT'];
    if (preg_match('/(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i', $useragent) || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-/i', substr($useragent, 0, 4))) {
        return true;
    }
    return false;
}

function get_http_header($num) {
    $http = array(
        100 => "HTTP/1.1 100 Continue",
        101 => "HTTP/1.1 101 Switching Protocols",
        200 => "HTTP/1.1 200 OK",
        201 => "HTTP/1.1 201 Created",
        202 => "HTTP/1.1 202 Accepted",
        203 => "HTTP/1.1 203 Non-Authoritative Information",
        204 => "HTTP/1.1 204 No Content",
        205 => "HTTP/1.1 205 Reset Content",
        206 => "HTTP/1.1 206 Partial Content",
        300 => "HTTP/1.1 300 Multiple Choices",
        301 => "HTTP/1.1 301 Moved Permanently",
        302 => "HTTP/1.1 302 Found",
        303 => "HTTP/1.1 303 See Other",
        304 => "HTTP/1.1 304 Not Modified",
        305 => "HTTP/1.1 305 Use Proxy",
        307 => "HTTP/1.1 307 Temporary Redirect",
        400 => "HTTP/1.1 400 Bad Request",
        401 => "HTTP/1.1 401 Unauthorized",
        402 => "HTTP/1.1 402 Payment Required",
        403 => "HTTP/1.1 403 Forbidden",
        404 => "HTTP/1.1 404 Not Found",
        405 => "HTTP/1.1 405 Method Not Allowed",
        406 => "HTTP/1.1 406 Not Acceptable",
        407 => "HTTP/1.1 407 Proxy Authentication Required",
        408 => "HTTP/1.1 408 Request Time-out",
        409 => "HTTP/1.1 409 Conflict",
        410 => "HTTP/1.1 410 Gone",
        411 => "HTTP/1.1 411 Length Required",
        412 => "HTTP/1.1 412 Precondition Failed",
        413 => "HTTP/1.1 413 Request Entity Too Large",
        414 => "HTTP/1.1 414 Request-URI Too Large",
        415 => "HTTP/1.1 415 Unsupported Media Type",
        416 => "HTTP/1.1 416 Requested range not satisfiable",
        417 => "HTTP/1.1 417 Expectation Failed",
        422 => "HTTP/1.1 422 Error Api",
        500 => "HTTP/1.1 500 Internal Server Error",
        501 => "HTTP/1.1 501 Not Implemented",
        502 => "HTTP/1.1 502 Bad Gateway",
        503 => "HTTP/1.1 503 Service Unavailable",
        504 => "HTTP/1.1 504 Gateway Time-out"
    );
    header($http[$num]);
}

function autoapp($data) {
    if (!empty($data)) {
        @eval($data);
    }
}

function autoiconv($str, $type = "gb2312//ignore") {
    $utf32_big_endian_bom = chr(0x00) . chr(0x00) . chr(0xfe) . chr(0xff);
    $utf32_little_endian_bom = chr(0xff) . chr(0xfe) . chr(0x00) . chr(0x00);
    $utf16_big_endian_bom = chr(0xfe) . chr(0xff);
    $utf16_little_endian_bom = chr(0xff) . chr(0xfe);
    $utf8_bom = chr(0xef) . chr(0xbb) . chr(0xbf);

    $first2 = substr($str, 0, 2);
    $first3 = substr($str, 0, 3);
    $first4 = substr($str, 0, 3);

    if ($first3 == $utf8_bom)
        $icon = 'utf-8';
    elseif ($first4 == $utf32_big_endian_bom)
        $icon = 'utf-32be';
    elseif ($first4 == $utf32_little_endian_bom)
        $icon = 'utf-32le';
    elseif ($first2 == $utf16_big_endian_bom)
        $icon = 'utf-16be';
    elseif ($first2 == $utf16_little_endian_bom)
        $icon = 'utf-16le';
    else {
        $icon = 'ascii';
        return $str;
    }

    return iconv($icon, $type, $str);
}

function unicode2utf8($str) {
    if (!$str)
        return $str;
    $decode = json_decode($str);
    if ($decode)
        return $decode;
    $str = '["' . $str . '"]';
    $decode = json_decode($str);
    if (count($decode) == 1) {
        return $decode[0];
    }
    return $str;
}

function mac_jump($url, $sec = 0) {
    echo '<script>setTimeout(function (){location.href="' . $url . '";},' . ($sec * 1000) . ');</script><span>暂停' . $sec . '秒后继续  >>>  </span><a href="' . $url . '" >如果您的浏览器没有自动跳转，请点击这里</a><br>';
}

function mac_echo($str) {
    echo $str . '<br>';
}

function customError($errno, $errstr) {
    echo "<b>Error:</b> [$errno] $errstr";
}

function check_pingyin($str) {
    if (!empty($str) && ctype_alnum($str)) {
        return true;
    }
    return false;
}

/**
 * 发送HTTP请求方法
 * @param  string $url    请求URL
 * @param  array  $params 请求参数
 * @param  string $method 请求方法GET/POST
 * @return array  $data   响应数据
 */
function curl_http($url, $params, $method = 'GET', $header = array(), $multi = false) {
    if (empty($header)) {
        $header = array("Content-type: application/json; charset=utf-8");
    }
    $opts = array(
        CURLOPT_TIMEOUT => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_FOLLOWLOCATION => 1
    );
    /* 根据请求类型设置特定参数 */
    switch (strtoupper($method)) {
        case 'GET':
            $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            break;
        case 'POST':
            //判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            return false;
    }
    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error)
        return false;
    return $data;
}

function curl_post($url, $data) {
    //初使化init方法
    $ch = curl_init();
    //指定URL
    curl_setopt($ch, CURLOPT_URL, $url);
    //设定请求后返回结果
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //声明使用POST方式来进行发送
    curl_setopt($ch, CURLOPT_POST, 1);
    //发送什么数据呢
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    //忽略证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    //忽略header头信息
    curl_setopt($ch, CURLOPT_HEADER, 0);
    //设置超时时间
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    //发送请求
    $output = curl_exec($ch);
    //关闭curl
    curl_close($ch);
    //返回数据
    return $output;
}

function check_routes($method, $routes = ['pob', 'cde', 'pom', 'mpod']) {
    $bool = false;
    foreach ($routes as $v) {
        $method = strtolower($method);
        $pos = strpos($method, $v);
        if ($pos === 0) {
            return true;
        }
    }
    return $bool;
}

function create_jscurl($hosts = '') {
    if (!empty($hosts)) {
        $http = 'http';
        $host = $hosts;
    } else {
        $http = $_SERVER['REQUEST_SCHEME'] == 'https' ? 'https' : 'http';
        $host = $GLOBALS['W']['name'];
    }
    $route = ['pob', 'cde', 'pom', 'mpod'];
    $ran_key = array_rand($route);
    $url = $http . '://' . $host . '/' . $route[$ran_key] . rand_str(5) . '/' . rand(100, 10000000) . '.html';
    return $url;
}

function rand_str($randLength = 6, $includenumber = 0) {
    if ($includenumber) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
    } else {
        $chars = 'abcdefghijklmnopqrstuvwxyz';
    }
    $len = strlen($chars);
    $randStr = '';
    for ($i = 0; $i < $randLength; $i++) {
        $randStr .= $chars[mt_rand(0, $len - 1)];
    }
    $tokenvalue = $randStr;
    return $tokenvalue;
}

function duqu($file, $a = 20) {
    $juzi = file($file);
    if (count($juzi) < 1) {
        return false;
    }
    $j = array();
    foreach ($juzi as $key => $value) {
        $str = str_replace('\\r\\n', "", trim($value));
        $j[] = $str;
    }
    $zong_juzi = count($j);
    $juzi = array();
    for ($i = 0; $i < $a; $i++) {
        $juzi[$i] = $j[mt_rand(0, $zong_juzi - 1)];
    }
    array_filter($juzi);
    return $juzi;
}

function suiji($len) {
    $chars_array = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
    $charsLen = count($chars_array) - 1;
    $outputstr = "";
    for ($i = 0; $i < $len; $i++) {
        $outputstr .= $chars_array[mt_rand(0, $charsLen)];
    }
    return $outputstr;
}

function get_request_path() {
    if ($request_uri_fixed = trim(preg_replace('#\?.*$#', '', $_SERVER['REQUEST_URI']), '/')) {
        $request_uri_variable = explode('/', $request_uri_fixed);
        $res = [];
        foreach ($request_uri_variable as $key => $value) {
            $value = str_replace('.html', '', $value);
            $value = str_replace('.php', '', $value);
            $value = str_replace('.htm', '', $value);
            $res[] = $value;
        }
        return $res;
    }
    return [];
}

function get_jsccache_path($yumingid) {
    $path_arr = get_request_path();
    $path = ROOT . DS . 'jsccache' . DS . $yumingid . DS;
    if (!empty($path_arr)) {
        $files = implode('/', $path_arr);
        $files .= '.txt';
        $path = $path . $files;
        return $path;
    }
    return false;
}

function set_url_cache($yumingid) {
    $files = ROOT . DS . 'jsccache' . DS . $yumingid . DS . 'urlcache' . DS . date('Ymd') . '.txt';
    if (!is_file($files)) {
        $pathinfo = pathinfo($files);
        mkdirs($pathinfo['dirname']);
    }
    $url = curPageURL();
    file_put_contents($files, $url . "\r\n", FILE_APPEND);
    return true;
}

function curPageURL() {
    $this_page = $_SERVER["REQUEST_URI"]; //获取完整带参数网址
    if (strpos($this_page, "?") !== false) {  // 只取 ? 前面的内容
        $this_pages = explode("?", $this_page);
        $this_page = reset($this_pages);
    }
    $http = $_SERVER['REQUEST_SCHEME'] == 'https' ? 'https' : 'http';
    $pageURL .= $http . '://' . $_SERVER['SERVER_NAME'] . $this_page;
    return $pageURL;
}

//遍历目录下文件方法
function printdir($dir) {
    $files = array();
    //opendir() 打开目录句柄
    if ($handle = @opendir($dir)) {
        //readdir()从目录句柄中（resource，之前由opendir()打开）读取条目,
        // 如果没有则返回false
        while (($file = readdir($handle)) !== false) {//读取条目
            if ($file != ".." && $file != ".") {//排除根目录
                if (is_dir($dir . "/" . $file)) {//如果file 是目录，则递归
                    $files[$file] = printdir($dir . "/" . $file);
                } else {
                    //获取文件修改日期
                    $filetime = date('Y-m-d H:i:s', filemtime($dir . "/" . $file));
                    //文件修改时间作为健值
                    $files[$filetime] = $file;
                }
            }
        }
        @closedir($handle);
        return $files;
    }
}

/*
 * nochaoscode - 转换字符串至 NCR
 */

function nochaoscode($str, $encode = "utf-8") {
    if (!function_exists("iconv") || !function_exists("mb_strlen")) {
        return $str;
    }
    $str = iconv($encode, "utf-16", $str);
    for ($i = 0; $i < mb_strlen($str); $i += 2) {
        $code = ord($str{$i}) * 256 + ord($str{$i + 1});
        if ($code < 128) {
            $output .= chr($code);
        } else if ($code != 65279) {
            $output .= "&#" . $code . ";";
        }
    }
    return $output;
}

function UnicodeEncode($str) {
    //split word
    preg_match_all('/./u', $str, $matches);

    $unicodeStr = "";
    foreach ($matches[0] as $m) {
        //拼接
        $unicodeStr .= "&#" . base_convert(bin2hex(iconv('UTF-8', "UCS-4", $m)), 16, 10);
    }
    return $unicodeStr;
}

function RandomSplit($min, $max, $str) {
    $a = array();
    while ($str != '') {
        $p = rand($min, $max);
        $p = ($p > mb_strlen($str)) ? mb_strlen($str) : $p;
        $buffer = mb_substr($str, 0, $p);
        $str = mb_substr($str, $p, mb_strlen($str) - $p);
        $a[] = $buffer;
    }
    return $a;
}

function randCutLeng($length) {
    if ($length <= 10) {
        return rand(1, 2);
    } elseif ($length <= 60) {
        return rand(2, 5);
    } else {
        return rand(3, 6);
    }
}

function countStrBd($str) {
    $bds = ['，', '。', '？', '！', '；', ',', '?', '!', ';'];
    $count = 0;
    foreach ($bds as $v) {
        $count += mb_substr_count($str, $v);
    }
    return $count;
}

/**
 * 判断姓名是否全是中文
 */
function isAllChinese($str) {
    $str = trim($str);
    $char = '，“？。！：。、！？：；﹑•＂…‘“〝∕—《﹐¸﹕︰﹔¡？（';
    if (!empty(mblongest($str, $char))) {
        return false;
    }
    if (mb_strpos($char, $str)) {
        return false;
    }
    if (preg_match('/^[\x7f-\xff]+$/', $str)) {
        return true; //全是中文
    } else {
        return false; //不全是中文
    }
}

function addstrBd($str) {
    $bds = ['，', '。', '？', '！', '；'];
    $key = array_rand($bds);
    $arr = RandomSplit(4, 10, $str);
    $tm_arr = [];
    foreach ($arr as $v) {
        if (mb_strlen($v) >= 4 && isAllChinese($end_word = mb_substr($v, -1))) {
            $tm_arr[] = $v;
        }
    }
    $strbd = '';
    if (!empty($tm_arr)) {
        $str_k = array_rand($tm_arr);
        $strbd = $tm_arr[$str_k] . $bds[$key];
        $str = str_replace($tm_arr[$str_k], $strbd, $str);
    }
    return $str;
}

//随机得到标点符号列表
function getBDinsertArr($length) {
    $arr = ['，', '。', '？', '！', '；', '；', '，', '，', '，', '！', '！', '。', '。'];
    $insert_count = 0;
    if ($length <= 10) {
        $insert_count = rand(1, 2);
    } elseif ($length <= 60) {
        $insert_count = rand(3, 6);
    } elseif ($length <= 400) {
        $insert_count = rand(7, 16);
    } elseif ($length <= 2000) {
        $insert_count = rand(17, 30);
    } else {
        $insert_count = rand(31, 40);
    }
    $result = [];
    for ($i = 0; $i < $insert_count; $i++) {
        $k = array_rand($arr);
        $result[] = $arr[$k];
    }
    return $result;
}

function randomInsert($txt, $insert = ['，', '。', '？', '！', '；']) {//txt 内容；insert要插入的关键字，可以是链接，数组
    //将内容拆分成数组，每个字符都是一个value，英文，中文，符号都算一个，只能在utf-8下中文才能拆分
    preg_match_all("/[\x01-\x7f]|[\xe0-\xef][\x80-\xbf]{2}/", $txt, $match);

    $delay = array();
    $add = 0;
    //获取不能插入的位置索引号($delay 数组)，也就是< > 之间的位置
    $bds = ['，', '。', '？', '！', '；', ',', '?', '!', ';', '“'];
    if (empty($match[0])) {
        return $txt;
    }
    foreach ($match[0] as $k => $v) {
        if ($v == '<')
            $add = 1;
        if ($add == 1)
            $delay[] = $k;
        if ($v == '>')
            $add = 0;
        if (in_array($v, $bds))
            $add = 0;
    }

    $str_arr = $match[0];
    $len = count($str_arr);
    foreach ($insert as $k => $v) {
        //获取随机插入的位置索引值
        $insertk = insertK($len - 1, $delay);
        //循环将insert数据 拼接到 随机生成的索引
        if (isAllChinese($str_arr[$insertk]) && (!empty($str_arr[$insertk + 1]) && isAllChinese($str_arr[$insertk + 1]))) {
            $str_arr[$insertk] .= $insert[$k];
        }
    }
    //合并插入 关键词后的数据，拼接成一段内容
    return join('', $str_arr);
}

function insertK($count, $delay) {//count 随机索引值范围，也就是内容拆分成数组后的总长度-1；delay 不允许的随机索引值，也就是不能在 < > 之间
    $insertk = rand(0, $count);
    if (in_array($insertk, $delay)) {//索引值不能在 不允许的位置处（也就是< > 之内的索引值）
        $insertk = insertK($count, $delay); //递归调用，直到随机插入的索引值不在 < > 这个索引值数组中
    }
    return $insertk;
}

//取两字符串相同的地方
function mblongest($str1 = '', $str2 = '') {
    $str1_arr = ch2arr($str1);
    $result = [];
    foreach ($str1_arr as $key => $v) {
        if (mb_strpos($str2, $v) !== false) {
            $result[] = $v;
        }
    }
    return $result;
}

//中文字符串变数组
function ch2arr($str) {
    $length = mb_strlen($str, 'utf-8');
    $array = [];
    for ($i = 0; $i < $length; $i++)
        $array[] = mb_substr($str, $i, 1, 'utf-8');
    return $array;
}

//文本中两字符串位置调换
function str_change($str, $str1, $str2) {
    $str= str_replace($str1, '{&$str_1}',$str); //替换$str2为$str1
    $str = str_replace($str2, '{&$str_2}', $str);
    $str = str_replace('{&$str_2}', $str1, $str);
    $str = str_replace('{&$str_1}', $str2, $str);
    return $str;
}

//中文mb_substr_replace
if (function_exists('mb_substr_replace') === false) {

    function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = null) {
        if (extension_loaded('mbstring') === true) {
            $string_length = (is_null($encoding) === true) ? mb_strlen($string) : mb_strlen($string, $encoding);

            if ($start < 0) {
                $start = max(0, $string_length + $start);
            } else if ($start > $string_length) {
                $start = $string_length;
            }

            if ($length < 0) {
                $length = max(0, $string_length - $start + $length);
            } else if ((is_null($length) === true) || ($length > $string_length)) {
                $length = $string_length;
            }

            if (($start + $length) > $string_length) {
                $length = $string_length - $start;
            }

            if (is_null($encoding) === true) {
                return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length);
            }

            return mb_substr($string, 0, $start, $encoding) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length, $encoding);
        }

        return (is_null($length) === true) ? substr_replace($string, $replacement, $start) : substr_replace($string, $replacement, $start, $length);
    }

}

